<template>
	<div class="base-info-page">
		<NavHeader
			:title="t('baseInfo.title', '基本信息')"
			:showStepProgress="true"
			:current="1"
		/>
		<div class="info-card-group">
			<!-- 卡片1：基本信息 -->
			<div class="info-card info-main-card">
				<div class="main-card-title">
					{{ t('baseInfo.title', '基本信息') }}
				</div>
				<div class="main-card-row">
					<span class="main-card-label">{{
						t('baseInfo.name', '姓名')
					}}</span>
					<van-field
						v-model="form.name"
						:placeholder="t('baseInfo.remarkPlaceholder', '请输入')"
						class="main-card-input"
						input-align="right"
					/>
				</div>
				<div class="main-card-row">
					<span class="main-card-label">{{
						t('baseInfo.phone', '联系方式')
					}}</span>
					<van-field
						v-model="form.contact"
						:placeholder="t('baseInfo.remarkPlaceholder', '请输入')"
						class="main-card-input"
						input-align="right"
					/>
				</div>
				<div class="main-card-row">
					<span class="main-card-label">{{
						t('baseInfo.address', '街道地址')
					}}</span>
					<van-field
						v-model="form.address"
						:placeholder="t('baseInfo.remarkPlaceholder', '请输入')"
						class="main-card-input"
						input-align="right"
					/>
				</div>
				<div class="main-card-row">
					<span class="main-card-label">{{
						t('baseInfo.city', '城市')
					}}</span>
					<van-field
						v-model="form.city"
						:placeholder="t('baseInfo.remarkPlaceholder', '请输入')"
						class="main-card-input"
						input-align="right"
					/>
				</div>
				<div class="main-card-row">
					<span class="main-card-label">{{
						t('baseInfo.state', '州')
					}}</span>
					<van-field
						v-model="form.state"
						:placeholder="t('baseInfo.remarkPlaceholder', '请输入')"
						class="main-card-input"
						input-align="right"
					/>
				</div>
				<div class="main-card-row">
					<span class="main-card-label">{{
						t('baseInfo.zipCode', '邮编')
					}}</span>
					<van-field
						v-model="form.zip_code"
						:placeholder="t('baseInfo.remarkPlaceholder', '请输入')"
						class="main-card-input"
						input-align="right"
					/>
				</div>
			</div>
			<!-- 期望上门日期卡片 -->
			<div class="info-card clickable" @click="onDateClick">
				<span class="card-label">{{
					t('baseInfo.expectDate', '期望上门日期')
				}}</span>
				<span class="card-value">
					<template
						v-if="
							form.selectedDates &&
							form.selectedDates.length === 2
						"
					>
						{{ formatDate(form.selectedDates[0]) }}-{{
							formatDate(form.selectedDates[1])
						}}<br />
						<span v-if="form.service_time">{{
							form.service_time
						}}</span>
					</template>
					<template v-else>{{
						t('delivery.placeholder', '请选择')
					}}</template>
				</span>
				<van-icon name="arrow" class="card-arrow" />
			</div>
			<DatePickerPopup
				v-model:show="showDatePicker"
				v-model:modelValue="form.selectedDates"
				v-model:timeValue="form.service_time"
			/>
			<!-- 卡片2：服务内容 -->
			<!-- 服务内容卡片 -->
			<div class="info-card clickable" @click="openServicePopup">
				<span class="card-label">{{
					t('baseInfo.service', '服务内容')
				}}</span>
				<span class="card-value">{{
					form.service || t('delivery.placeholder', '请选择')
				}}</span>
				<van-icon name="arrow" class="card-arrow" />
			</div>
			<ServiceSelectPopup
				v-model:show="showServicePopup"
				v-model:modelValue="form.service"
				:serviceList="serviceList"
			/>
			<!-- 卡片3：额外需求 -->
			<div class="info-card clickable" @click="onExtraClick">
				<span class="card-label">{{
					t('baseInfo.extra', '额外需求')
				}}</span>
				<span class="card-value">{{
					form.extra || t('delivery.placeholder', '请选择')
				}}</span>
				<van-icon name="arrow" class="card-arrow" />
			</div>

			<ExtraSelectPopup
				v-model:show="showExtraPopup"
				v-model:modelValue="extraList"
			/>
			<!-- 卡片4：备注 -->
			<div class="info-card">
				<span class="card-label">{{
					t('baseInfo.remark', '备注')
				}}</span>
				<van-field
					v-model="form.remark"
					:placeholder="t('baseInfo.remarkPlaceholder', '请输入')"
					class="card-input"
				/>
			</div>
		</div>
		<!-- //占空间 -->
		<div style="height: 100px"></div>
		<div class="bottom-btn-bar">
			<button class="btn-prev" @click="onPrevClick">
				{{ t('common.prev', '上一步') }}
			</button>
			<button class="btn-next" @click="onNextClick">
				{{ t('common.next', '下一步') }}
			</button>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import NavHeader from '@/components/NavHeader.vue'
import { useRouter, useRoute } from 'vue-router'
import DatePickerPopup from '@/components/DatePickerPopup.vue'
import { getServiceList } from '@/api/user'
import type { ServiceItem } from '@/types/service'
import ServiceSelectPopup from '@/components/ServiceSelectPopup.vue'
import ExtraSelectPopup from '@/components/ExtraSelectPopup.vue'
import { useOrderStore } from '@/stores/order'
import { showToast } from 'vant'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()
const orderStore = useOrderStore()
const route = useRoute()

const showDatePicker = ref(false)
const isDateInited = ref(false)
const serviceList = ref<ServiceItem[]>([])
const showServicePopup = ref(false)
const showExtraPopup = ref(false)
const extraList = ref<string[]>(
	Array.isArray(orderStore.customer.additional_requirements)
		? orderStore.customer.additional_requirements
		: []
)

function openServicePopup() {
	showServicePopup.value = true
}

// 只有第一次打开弹窗时会自动选中"今天和明天"。
watch(showDatePicker, (val) => {
	if (val && !isDateInited.value) {
		const today = new Date()
		const tomorrow = new Date()
		tomorrow.setDate(today.getDate() + 1)
		form.value.selectedDates = [today, tomorrow]
		isDateInited.value = true
	}
})

const form = ref({
	name: orderStore.customer.name,
	contact: orderStore.customer.mobile,
	address: orderStore.customer.address,
	city: orderStore.customer.city,
	state: orderStore.customer.state,
	zip_code: orderStore.customer.zip_code,
	service: '',
	extra: Array.isArray(orderStore.customer.additional_requirements)
		? orderStore.customer.additional_requirements.join(', ')
		: '',
	date: '',
	selectedDates: orderStore.customer.service_date
		? orderStore.customer.service_date.split(',').map((d) => new Date(d))
		: [],
	service_time: orderStore.customer.service_time
		? orderStore.customer.service_time.split(',').join('-')
		: '',
	remark: orderStore.customer.remarks,
})

watch(extraList, (val) => {
	form.value.extra = val.length ? val.join(', ') : ''
	orderStore.customer.additional_requirements = val
})

watch(
	() => form.value.service,
	(serviceName) => {
		if (!serviceName) return
		// 遍历 serviceList 找到对应的 category 和 service
		for (const category of serviceList.value) {
			const service = category.serviceLists.find(
				(s) => s.name === serviceName
			)
			if (service) {
				orderStore.customer.service_category_id = category.id
				orderStore.customer.service_id = service.id
				break
			}
		}
	}
)

watch(
	() => form.value.name,
	(val) => {
		orderStore.customer.name = val
	}
)

watch(
	() => form.value.contact,
	(val) => {
		orderStore.customer.mobile = val
	}
)

watch(
	() => form.value.address,
	(val) => {
		orderStore.customer.address = val
	}
)

watch(
	() => form.value.city,
	(val) => {
		orderStore.customer.city = val
	}
)

watch(
	() => form.value.state,
	(val) => {
		orderStore.customer.state = val
	}
)

watch(
	() => form.value.zip_code,
	(val) => {
		orderStore.customer.zip_code = val
	}
)

watch(
	() => form.value.selectedDates,
	(val) => {
		// 转字符串存储
		orderStore.customer.service_date = Array.isArray(val)
			? val.map((d) => d.toISOString().slice(0, 10)).join(',')
			: ''
	},
	{ deep: true }
)

watch(
	() => form.value.service_time,
	(val) => {
		// 还原成逗号分隔
		orderStore.customer.service_time = val ? val.replace('-', ',') : ''
	}
)

watch(
	() => form.value.remark,
	(val) => {
		orderStore.customer.remarks = val
	}
)

onMounted(() => {
	console.log('BaseInfo组件挂载')
	getServiceList().then((res) => {
		console.log(res)
		const items = res.data.items // items: ServiceItem[]
		console.log(items)
		serviceList.value = items
		// 自动回显服务内容
		const category = serviceList.value.find(
			(item) => item.id === orderStore.customer.service_category_id
		)
		if (category) {
			const service = category.serviceLists.find(
				(s) => s.id === orderStore.customer.service_id
			)
			if (service) {
				form.value.service = service.name
			}
		}
	})
})

const router = useRouter()


function onServiceClick() {
	openServicePopup()
}
function onExtraClick() {
	showExtraPopup.value = true
}
function onDateClick() {
	showDatePicker.value = true
	if (!form.value.service_time) {
		form.value.service_time = '08:00-12:00'
	}
}
function onPrevClick() {
	router.back()
}
function onNextClick() {
	// 必填项校验
	if (!form.value.name) {
		showToast(t('baseInfo.fillName'))
		return
	}
	if (!form.value.contact) {
		showToast(t('baseInfo.fillContact'))
		return
	}
	if (!form.value.address) {
		showToast(t('baseInfo.fillAddress'))
		return
	}
	if (!form.value.city) {
		showToast(t('baseInfo.fillCity'))
		return
	}
	if (!form.value.state) {
		showToast(t('baseInfo.fillState'))
		return
	}
	if (!form.value.zip_code) {
		showToast(t('baseInfo.fillZipCode'))
		return
	}
	// if (!form.value.service) {
	// 	showToast(t('baseInfo.selectService'))
	// 	return
	// }
	if (!form.value.selectedDates || form.value.selectedDates.length !== 2) {
		showToast(t('baseInfo.selectDate'))
		return
	}
	// 其它必填项可按需补充

	// 校验通过，跳转
	router.push({
		name: 'InstallationPosition',
	})
}

function formatDate(date: Date) {
	if (!date) return ''
	const m = (date.getMonth() + 1).toString().padStart(2, '0')
	const d = date.getDate().toString().padStart(2, '0')
	return `${m}/${d}`
}
</script>

<style scoped>
.base-info-page {
	background: #f3f4f6;
	min-height: 100vh;
	padding-bottom: 24px;
}

.info-card-group {
	padding: 16px 0 0 0;
	display: flex;
	flex-direction: column;
	gap: 12px;
	align-items: center;
}

.info-card {
	width: 95%;
	max-width: 450px;
	height: 60px;
	border-radius: 15px;
	background: #fff;
	box-shadow: none;
	margin: 0;
	display: flex;
	align-items: center;
	border: 1px solid #eee;
	padding: 0 16px;
	position: relative;
}

.card-title {
	font-size: 16px;
	font-family: 'PingFang SC', sans-serif;
	font-weight: 600;
	color: #000;
	letter-spacing: -0.3px;
}

.card-row {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 16px;
	min-height: 44px;
	border-bottom: 0.5px solid #b1b1b2;
}

.card-row:last-child {
	border-bottom: none;
}

.card-label {
	font-size: 16px;
	font-family: 'PingFang SC', sans-serif;
	font-weight: 600;
	color: #000;
	letter-spacing: -0.3px;
}

.card-value {
	flex: 1;
	text-align: right;
	font-size: 14px;
	color: #b1b1b2;
	font-family: 'PingFang SC', sans-serif;
	font-weight: 600;
	margin-left: 12px;
}

.card-arrow {
	font-size: 20px;
	color: #b1b1b2;
	margin-left: 4px;
}

.card-input {
	flex: 1;
	text-align: right;
	font-size: 14px;
	color: #b1b1b2;
	font-family: 'PingFang SC', sans-serif;
	font-weight: 600;
	background: transparent;
	border: none;
	margin-left: 12px;
}

.clickable {
	cursor: pointer;
}

.info-main-card {
	width: 95%;
	max-width: 450px;
	height: 314px;
	border-radius: 15px;
	background: #fff;
	box-shadow: none;
	margin: 0;
	padding: 0 0 0 0;
	display: flex;
	flex-direction: column;
	align-items: stretch;
	border: 1px solid #eee;
	position: relative;
}

.main-card-title {
	font-size: 16px;
	font-family: 'PingFang SC', sans-serif;
	font-weight: 600;
	color: #000;
	letter-spacing: -0.3px;
	margin: 16px 0 0 16px;
}

.main-card-row {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 16px;
	min-height: 44px;
	position: relative;
}

.main-card-row:not(:last-child)::after {
	content: '';
	position: absolute;
	left: 16px;
	right: 16px;
	bottom: 0;
	height: 0.5px;
	background: #b1b1b2;
}

.main-card-label {
	font-size: 14px;
	color: #3c3c3c;
	font-family: 'PingFang SC', sans-serif;
	font-weight: 500;
}

.main-card-input {
	flex: 1;
	text-align: right;
	font-size: 14px;
	color: #b1b1b2;
	font-family: 'PingFang SC', sans-serif;
	font-weight: 600;
	background: transparent;
	border: none;
	margin-left: 12px;
	padding-right: 4px;
}

::v-deep(.main-card-input .van-field__control) {
	text-align: right;
	padding-right: 4px;
}

.bottom-btn-bar {
	position: fixed;
	left: 0;
	bottom: 0;
	width: 100vw;
	display: flex;
	justify-content: center;
	align-items: center;
	background: #fff;
	padding: 12px 0 12px 0;
	z-index: 20;
	gap: 16px;
	box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.03);
}

.btn-prev {
	width: 108px;
	height: 60px;
	border-radius: 10px;
	background: #e7e7e7;
	color: #333a44;
	font-size: 20px;
	font-family: 'PingFang SC', sans-serif;
	font-weight: 600;
	border: none;
	outline: none;
	letter-spacing: -0.3px;
	cursor: pointer;
}

.btn-next {
	width: 232px;
	height: 60px;
	border-radius: 10px;
	background: #0065d1;
	color: #fff;
	font-size: 20px;
	font-family: 'PingFang SC', sans-serif;
	font-weight: 600;
	border: none;
	outline: none;
	letter-spacing: -0.3px;
	cursor: pointer;
}
</style>
